package com.fpc.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author: jingwenjuan
 * @Description: url转成MultipartFile
 */
@Slf4j
public class UrlToMultipartFile {

    /**
     * inputStream 转 File
     */
    public static File inputStreamToFile(InputStream ins, String name) throws Exception{
        //System.getProperty("java.io.tmpdir")临时目录+File.separator目录中间的间隔符+文件名
        File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
//        if (file.exists()) {
//            return file;
//        }
        OutputStream os = new FileOutputStream(file);
        int bytesRead;
        int len = 8192;
        byte[] buffer = new byte[len];
        while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        return file;
    }

    /**
     * file转multipartFile
     */
    public static MultipartFile fileToMultipartFile(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item=factory.createItem(file.getName(),"text/plain",true,file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }

    /**
     * url转MultipartFile
     */
    public static MultipartFile urlToMultipartFile(String url) throws Exception {
        File file = null;
        MultipartFile multipartFile = null;
        try {
            HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
            httpUrl.connect();
            file = UrlToMultipartFile.inputStreamToFile(httpUrl.getInputStream(),"template.png");
            log.info("---------"+file+"-------------");

            multipartFile = UrlToMultipartFile.fileToMultipartFile(file);
            httpUrl.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return multipartFile;
    }
    
    
    public static void main(String [] agr) {
    	 String url="https://img2.baidu.com/it/u=2147843660,3054818539&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=313";
    	 try {
			MultipartFile file = UrlToMultipartFile.urlToMultipartFile(url);
			 String path = "D:\\upload\\";
		        // 获取文件名(包括后缀)
		        String fileName = file.getOriginalFilename();
		        try (FileOutputStream fos = new FileOutputStream(path + fileName)) {
		            fos.write(file.getBytes());
		            //return "文件上传成功";
		        } catch (Exception e) {
		            log.error("file upload failed, fileName = {}", file.getOriginalFilename(), e);
		        }
			
		} catch (Exception e) {
			e.printStackTrace();
		}
      
       
    	
    }
    
}
/*
// jar包
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.2.2</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

// 测试
@ApiOperation("批量上传图片")
    @PostMapping("/uploadImgs")
    public ApiResultDto<List<UploadBack>> uploadImgs(@Valid @RequestBody UploadParam param) throws Exception {
        List<String> urls = param.getUrls();
        List<UploadBack> backs = new ArrayList<>();
        if (!CollectionUtils.isEmpty(urls)) {
            System.out.println("----------"+urls.size());
            urls.forEach(url-> System.out.println("图片链接-------"+url+"---------"));
            for (String url : urls) {
                MultipartFile file = UrlToMultipartFile.urlToMultipartFile(url);
                ApiResultDto<UploadBack> res = uploadToALi(file, param);
                if(res.getCode().equals(200)) {
                    backs.add(res.getData());
                }else{
                    return new ApiResultDto<>(400,"上传失败!");
                }
            }
            backs.forEach(back-> System.out.println("----本地图片地址---"+back+"--------"));
        }else{
            log.info("---------没有图片链接--------"+urls);
        }

        return new ApiResultDto<>(backs);
    }

    @ApiOperation("上传文件")
    @PostMapping("/uploadFile")
    public ApiResultDto<UploadBack> uploadToALi(MultipartFile file,@Valid  UploadParam param) throws IOException {
        InputStream inputStream = file.getInputStream();
        param.setUploadTime(new Date());
        param.setFileName(file.getOriginalFilename());
        String dataUrl = fileUploadService.uploadToOSS(inputStream, param).getData();
        System.out.println("-----------URL----------"+dataUrl);

        return articleService.addAttachment(param.getArticleId(),dataUrl,param.getUploadType(),file.getOriginalFilename());
    }*/